package com.blobfish.fiction.common.download;

import com.blobfish.fiction.book.service.impl.BookServiceImpl;
import com.blobfish.fiction.common.base.knowledge.DataDictKnowledge;
import com.blobfish.fiction.common.model.Book;
import com.jfinal.aop.Aop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.redis.Redis;

import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 下载队列
 * @author huangbo
 */
public class DownloadQueue extends ArrayBlockingQueue<String> {
    private BookServiceImpl bookService;

    public DownloadQueue(int capacity, BookServiceImpl bookService) {
        super(capacity);
        this.bookService = bookService;
    }

    @Override
    public void put(String bookNo) throws InterruptedException {
        if (!isDumpDownloadTask(bookNo)) {
            synchronized (this) {
                if (!isDumpDownloadTask(bookNo)) {
                    Redis.use("master").sadd(PropKit.get("cacheName.DOWNLOADED_BOOK_NO"), bookNo);
                    Book book = bookService.getByBookNo(bookNo);
                    book.setState(DataDictKnowledge.BookStateEnum.DOWNLOADING.getDataCode());
                    book.update();
                    super.put(bookNo);
                }
            }
        }
    }

    /**
     * 添加断点下载任务
     * @param bookNo 待添加的bookNo
     * @throws InterruptedException
     */
    public void putBreakpointDownload(String bookNo) throws InterruptedException {
        Redis.use("master").sadd(PropKit.get("cacheName.DOWNLOADED_BOOK_NO"), bookNo);
        super.put(bookNo);
    }

    @Override
    public String take() throws InterruptedException {
        return super.take();
    }

    /**
     * 判断是否为重复下载任务
     * @param bookNo
     * @return
     */
    private boolean isDumpDownloadTask(String bookNo) {
        boolean isDump = false;
        Iterator<String> it = this.iterator();
        while(it.hasNext()) {
            String item = it.next();
            if (item.equals(bookNo)) {
                isDump = true;
                break;
            }
        }
        if (!isDump) {
            isDump = bookService.isDownloaded(bookNo);
        }
        return isDump;
    }
}
